package com.itheima.behaviour.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.behaviour.dto.UnLikesBehaviorDto;
import com.itheima.behaviour.feign.ApBehaviourEntryFeign;
import com.itheima.behaviour.pojo.ApBehaviorEntry;
import com.itheima.behaviour.pojo.ApUnlikesBehavior;
import com.itheima.behaviour.mapper.ApUnlikesBehaviorMapper;
import com.itheima.behaviour.service.ApUnlikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.pojo.Result;
import com.itheima.common.util.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * APP不喜欢行为表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-08-30
 */
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements ApUnlikesBehaviorService {

    @Autowired
    private ApBehaviourEntryFeign apBehaviourEntryFeign;

    @Autowired
    private ApUnlikesBehaviorMapper apUnlikesBehaviorMapper;

    /***
     * 不喜欢的行为
     * @param dto
     */
    @Override
    public void unlikes(UnLikesBehaviorDto dto) {
        //1:查询用户的信息（游客或者系统会员的Entry）
        Integer userId = RequestContext.getNodeValue("id");
        Result<ApBehaviorEntry> entryResult = apBehaviourEntryFeign.getByEquipmentIdOrUserId(dto.getEquipmentId(), userId);
        ApBehaviorEntry entry = entryResult.getData();

        if(entry!=null) {
            //2:查询当前用户操作的喜欢行为数据
            QueryWrapper<ApUnlikesBehavior> queryWrapper = new QueryWrapper<ApUnlikesBehavior>();
            queryWrapper.eq("entry_id",entry.getId());
            queryWrapper.eq("article_id",dto.getArticleId());
            ApUnlikesBehavior apUnlikesBehavior = apUnlikesBehaviorMapper.selectOne(queryWrapper);

            //3:如果不存在对应的数据，并且是点击不喜欢的时候，添加
            if(dto.getType()==0 && apUnlikesBehavior==null){
                apUnlikesBehavior = new ApUnlikesBehavior();
                apUnlikesBehavior.setEntryId(entry.getId());
                apUnlikesBehavior.setArticleId(dto.getArticleId());
                apUnlikesBehavior.setType(dto.getType());
                apUnlikesBehavior.setCreatedTime(LocalDateTime.now());
                apUnlikesBehaviorMapper.insert(apUnlikesBehavior);
            }else if(dto.getType()==1){
                //4:如果存在对应的数据，则修改
                apUnlikesBehavior.setType(dto.getType());
                apUnlikesBehaviorMapper.updateById(apUnlikesBehavior);
            }
        }
    }
}